package test;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.io.Files;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;

import java.io.File;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by urfresh.mark on 2017/2/27.
 */
public class MongoSave3 {
    
    public MongoClient mongClient() throws Exception {
        MongoClient client = new MongoClient(
                Arrays.asList(
                        new ServerAddress("120.26.8.17", 27017)),
                Arrays.asList(
                        MongoCredential.createCredential("app_event_track", "app_event_track", "601ae08bc3ee0f2".toCharArray())
                ),
                MongoClientOptions.builder()
                        .socketKeepAlive(true)
                        .connectionsPerHost(10)
                        .threadsAllowedToBlockForConnectionMultiplier(10)
                        .connectTimeout(5000)
                        .maxWaitTime(5000)
//                        .requiredReplicaSetName(mongoReplicaSet)
//                        .readPreference(ReadPreference.secondaryPreferred())
                        .socketTimeout(1000)
                        .build());
        return client;
    }
    
    public SimpleMongoDbFactory mongoFactory() throws Exception {
        return new SimpleMongoDbFactory(mongClient(), "app_event_track");
    }
    
    public MongoTemplate mongoTemplate() throws Exception {
        return new MongoTemplate(mongoFactory());
    }
    
    public static void main(String[] args) throws Exception {
        MongoSave3 mongoSave = new MongoSave3();
        MongoTemplate mongoTemplate = mongoSave.mongoTemplate();
        AtomicInteger i = new AtomicInteger();
        Files.readLines(new File("C:\\Users\\urfresh.mark\\Desktop\\13.log"), Charset.forName("utf-8"))
                .stream()
                .forEach(s -> {
                    JSONObject obj = JSON.parseObject(s);
                    obj.put("createTime", obj.getString("submitTime"));
                    mongoTemplate.save(obj.toJSONString(), "event_track");
                    System.out.println(i.addAndGet(1)+","+obj);
                });
    }
    
}
